package facetest.az26;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程 交叉输出 A1B2C3......Z26
 */
public class LockTest {
    static Thread t1, t2;
    String[] zimuArr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", ",M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    String[] numArr = new String[zimuArr.length];
    Lock lock = new ReentrantLock();
    Condition t1Con = lock.newCondition();
    Condition t2Con = lock.newCondition();


    {
        for (int i = 0; i < zimuArr.length; i++) {
            numArr[i] = (i + 1) + "";
        }

    }

    AtomicInteger i = new AtomicInteger(0);

    @Test
    public void test() {

        t1 = new Thread(() -> {
            lock.lock();
            i.set(1);

            for (String s : zimuArr) {
                System.out.println(s);
                t2Con.signal();
                try {
                    t1Con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
            t2Con.signal();

            lock.unlock();


        });
        t2 = new Thread(() -> {
            lock.lock();
            if (i.get() != 1) {
                try {
                    t2Con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            for (String s : numArr) {
                t1Con.signal();
                System.out.println(s);
                try {
                    t2Con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            t1Con.signal();
            lock.unlock();
        });
        t2.start();
        t1.start();

        while (true) ;
    }
}
